$(function() {
    var dev_token = '13162165337000000000013162165337';
    // Get Url Type
    function getUrlType(req) {
        if (!req.url)
            return null;
        var arr = req.url.split('?')[0].split('.')[3].split('/');
        var type = '/' + arr[2] + '/' + arr[3];
        return type;
    }
    // Cut Url Path
    function getUrlPath(req) {
        var url = req.url.split('.')[3];
        url = url.substr(url.indexOf('/'));
        return url;
    }
    // Get Req
    function getReq(id) {
        for (i in requests) {
            var req = requests[i];
            if (req.id == id) {
                return req;
            }
        }
        return null;
    }
    // Init Data
    var requests = [];
    var types = [];
    $.get('postman.json', function(json) {
        var api = JSON.parse(json);
        requests = api.requests;
        // To Types
        var test = {};
        for (i in requests) {
            var req = requests[i];
            var type = getUrlType(req);
            if (type && !test[type]) {
                test[type] = true;
                types.push(type);
            }
        }
        types.sort();
        showMenu();
    })
    // Show Menu
    function showMenu() {
        $('.menu').empty();
        for (var i in types) {
            var type = types[i];
            html = '<ul class="menu-1">';
            html += '    <h4>' + type + '</h4>';
            html += '    <ul class="menu-2">';
            for (var i in requests) {
                var req = requests[i];
                if (type == getUrlType(req)) {
                    html += '        <li id="' + req.id + '" title="' + req.name + '">' + req.name + '</li>';
                }
            }
            html += '    </ul>';
            html += '</ul>';
            $('.menu').append(html);
        }
        bindUI();
    }
    // UI Bind
    function bindUI() {
        $('.menu-1 h4').click(function() {
            $(this).parents('.menu-1').addClass('active').siblings().removeClass('active');
        })
        $('.menu-2 li').click(function() {
            $(this).parents('.menu-1').addClass('active');
            $(this).addClass('active').siblings().removeClass('active');
            var id = $(this).attr('id');
            var req = getReq(id);
            if (req) {
                $('#name').text(req.name);
                $('#method').text(req.method);
                $('#url').val(getUrlPath(req));
                if (req.method == 'GET') {
                    $('#data').val('');
                } else if (typeof req.data === 'string') {
                    $('#data').val(req.data.replace(/\t/g, '  '));
                } else {
                    $('#data').val('');
                }
                $('#res').val('');
            }
        })
        $('.menu-2 li')[0].click();
    }
    // On Request
    $('#test').click(function() {
        var url = $('#url').val().trim();
        var method = $('#method').text()
        var str = $('#data').val() || '';
        if (method == 'POST') {
            try {
                var obj = JSON.parse(str);
                str = JSON.stringify(obj);
            } catch (e) {
                alert('请求参数JSON格式错误')
                return false;
            }
        }
        $.ajax({
            url: url,
            type: method,
            data: str,
            dataType: 'text',
            contentType: 'application/json',
            headers: { token: dev_token },
            success: function(res) {
                $('#res').val(res);
                var resObj = JSON.parse(res);
                if (resObj.data && resObj.data.token) {
                    dev_token = resObj.data.token;
                }
                if (Array.isArray(resObj.data)) {
                    window.resData = resObj.data;
                } else if (resObj.data && Array.isArray(resObj.data.items)) {
                    window.resData = resObj.data.items;
                }
                tableView();
            }
        });
    })
    // Table View
    function tableView() {
        if (window.resData) {
            var items = window.resData;
            var keys = Object.keys(items[0]);
            var filter = $('em').map(function() { return $(this).text() });
            for (var i in filter) {
                var index = keys.indexOf(filter[i]);
                if (index > -1) {
                    keys.splice(index, 1);
                }
            }
            $('thead').empty();
            var html = '<tr>'
            for (var i in keys) {
                html += '<th title="隐藏' + keys[i] + '列">' + keys[i] + '</th>';
            }
            $('thead').append(html + '</tr>');
            $('tbody').empty();
            for (var i in items) {
                var html = '<tr>'
                for (var j in keys) {
                    html += '<td>' + items[i][keys[j]] + '</td>';
                }
                $('tbody').append(html + '</tr>');
            }
            $('.data-box').show();
        } else {
            $('.data-box').hide();
        }
    }
    $(document).on('click', 'th', function() {
        var col = $(this).text().trim();
        $('#filter').append('<em>' + col + '</em>')
        tableView();
    });
    $(document).on('click', 'em', function() {
        $(this).remove();
        tableView();
    });
})